package cn.kgc.spring.proxy.cglib;

import cn.kgc.spring.service.TeacherService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: mosin
 * @version: v1.0  2022/10/13
 */
public class CGlibProxy {

    public static void main(String[] args) {

        // Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() )
        //被代理对象  没有实现任何的接口  需要使用cglib的代理方式
        TeacherService teacherService = new TeacherService();

        // 生成代理对象
        Enhancer enhancer = new Enhancer();
        // enhancer 设置类加载器
        ClassLoader classLoader = CGlibProxy.class.getClassLoader();
        enhancer.setClassLoader(classLoader);
        // 设置代理类的父类  基于继承实现 父子关系
        enhancer.setSuperclass(TeacherService.class);

        //设置自回调对象   增强的业务
        MethodInterceptor methodInterceptor =  new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("-----------进入intercept方法-------------");
                //System.out.println(method.getName());

                try {
                    System.out.println("---------开启事务------------");
                    Object invoke = method.invoke(teacherService, args);
                    System.out.println("---------提交事务------------");
                    return invoke;
                } catch (Exception e) {
                    System.out.println("---------回滚事务------------");
                    e.printStackTrace();
                }
                return null;
            }
        };

        enhancer.setCallback(methodInterceptor);

        //create()
        TeacherService o = (TeacherService) enhancer.create();

        Integer line = o.add();
        System.out.println(line);

    }
}
